package com.loren.designer.web.controller;

import com.loren.designer.data.properties.DesignerProperties;
import com.loren.designer.data.resp.SuccessResponse;
import com.loren.designer.exception.BusinessException;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@Slf4j
@RestController
@AllArgsConstructor
public class FileController {

    private final DesignerProperties designerProperties;

    private static final String FILE_PREFIX = "et-designer-";

    @PostMapping("/file/upload")
    public SuccessResponse upload(@RequestParam("file") MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isBlank(originalFilename)) {
            throw new BusinessException("未知文件名，上传文件失败");
        }
        String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = FILE_PREFIX + IdWorker.getId() + fileType;
        File destFile = new File(this.designerProperties.getFile().getUploadPath() + "/" + filename);
        if (destFile.getParentFile().mkdirs()) {
            log.debug("mkdir folder, path = {}", destFile.getParentFile().getAbsolutePath());
        }
        file.transferTo(destFile);
        String fileUrl = "/images/" + filename;
        return SuccessResponse.success(fileUrl);
    }

    @GetMapping(value = "/images/{filename}", produces = MediaType.IMAGE_JPEG_VALUE)
    public InputStreamResource imageView(@PathVariable("filename") String filename, HttpServletResponse response) throws IOException {
        File file = new File(this.designerProperties.getFile().getUploadPath() + "/" + filename);
        if (!file.exists()) {
            // 如果文件不存在，返回404页面
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return null;
        }
        return new InputStreamResource(new FileInputStream(file));
    }
}
